<template>
  <div>
    <div class="container" v-if="!dciomshow">
      <Breadcrumb />
      <a-card class="data-card">
        <a-row>
          <a-col :flex="1">
            <a-form
              :model="formModel"
              :label-col-props="{ span: 6 }"
              :wrapper-col-props="{ span: 18 }"
            >
              <a-row :gutter="20">
                <a-col :span="5">
                  <a-form-item field="caseName" label="病例名称">
                    <a-input
                      v-model="formModel.caseName"
                      placeholder="请输入病例名称"
                      allow-clear
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="5">
                  <a-form-item field="deptId" label="病例分类">
                    <a-select
                      v-model="formModel.caseTypeId"
                      check-strictly
                      :options="typedata"
                      placeholder="请选择所在分类"
                      :field-names="{
                        label: 'caseTypeName',
                        value: 'caseTypeId',
                      }"
                      :show-all-levels="false"
                      allow-clear
                    ></a-select>
                  </a-form-item>
                </a-col>

                <a-col :span="5">
                  <a-space :size="18">
                    <a-button @click="openAdd()" type="primary">
                      <template #icon>
                        <icon-plus />
                      </template>
                      新增
                    </a-button>
                    <a-button type="primary" @click="onPageChange(1)">
                      <template #icon>
                        <icon-search />
                      </template>
                      搜索
                    </a-button>
                    <a-button @click="reset">
                      <template #icon>
                        <icon-refresh />
                      </template>
                      重置
                    </a-button>
                    <!-- <a-button type="primary" @click="openOper">
										操作日志
									</a-button> -->
                  </a-space>
                </a-col>
              </a-row>
            </a-form>
          </a-col>
        </a-row>
        <a-divider style="margin-top: 0" />
        <a-table
          row-key="caseId"
          v-model:selectedKeys="caseIds"
          :loading="loading"
          page-position="bottom"
          :pagination="pagination"
          :columns="columns"
          :data="renderData"
          :bordered="false"
          @page-change="onPageChange"
          @page-size-change="onPageSizeChange"
        >
          <template #option="{ record }">
            <a-space :size="18">
              <!-- <a-button status="danger" @click="openDelete(record)">
              删除
            </a-button> -->
              <a-upload
                ref="uploadRef"
                :custom-request="
                  (option) => customRequest(option, record.caseId)
                "
                :limit="1"
                accept=".zip"
              />
              <a-button
                type="primary"
                status="success"
                @click="checksee(record.caseId)"
                >查看</a-button
              >
              <a-button @click="openEdit(record)" type="outline">
                编辑信息
              </a-button>
              <a-button status="danger" @click="openDelete(record)">
                删除
              </a-button>
            </a-space>
          </template>

          <template #url="{ record }">
            <a-space :size="18">
              <div class="imgbox">
                <img
                  :src="`${base + record.url}`"
                  @error="handleImgError"
                  alt=""
              /></div>
            </a-space>
          </template>
        </a-table>
      </a-card>
      <!-- 添加菜单 -->
      <a-modal
        v-model:visible="addShow"
        @cancel="handleCancel"
        :on-before-ok="handleCheck"
        :mask-closable="false"
        unmountOnClose
      >
        <template #title> 病例 </template>
        <a-form ref="addModel" :rules="rules" :model="addForm">
          <a-form-item field="status" label="是否开放" v-if="addForm.caseId">
            <a-switch
              v-model="addForm.status"
              :checked-value="`1`"
              :unchecked-value="`0`"
            />
          </a-form-item>
          <a-form-item field="caseTypeId" label="病例分类">
            <a-select
              v-model="addForm.caseTypeId"
              check-strictly
              :options="typedata"
              placeholder="请选择所在分类"
              :field-names="{
                label: 'caseTypeName',
                value: 'caseTypeId',
              }"
              :show-all-levels="false"
              allow-clear
            ></a-select>
          </a-form-item>
          <a-form-item field="caseName" label="病例名称">
            <a-input
              v-model="addForm.caseName"
              size="large"
              placeholder="请输入病例名称"
            />
          </a-form-item>

          <a-form-item field="situation" label="患者情况">
            <a-textarea
              v-model="addForm.situation"
              size="large"
              placeholder="请输入患者情况"
            />
          </a-form-item>
          <a-form-item field="imgFeatures" label="影像表现">
            <a-textarea
              v-model="addForm.imgFeatures"
              size="large"
              placeholder="请输入影像表现"
            />
          </a-form-item>

          <a-form-item field="diagnosticConclusion" label="诊断结论">
            <a-textarea
              v-model="addForm.diagnosticConclusion"
              size="large"
              placeholder="请输入诊断结论"
            />
          </a-form-item>

          <a-form-item field="url" label="图片封面">
            <!-- :custom-request="tponProgress"  @change="tponChange"-->
            <a-upload
              :show-file-list="false"
              @progress="tponProgress"
              accept="image/*"
            >
              <template #upload-button>
                <div
                  style="
                    background-color: var(--color-fill-2);
                    color: var(--color-text-1);
                    border: 1px dashed var(--color-fill-4);
                    height: 100px;
                    width: 100px;
                    border-radius: 2;
                    line-height: 100px;
                    text-align: center;
                  "
                >
                  <img
                    v-if="addForm.url"
                    :src="`${base + addForm.url}`"
                    alt=""
                    style="height: 100px; width: 100px"
                  />
                  <div v-else>上传图片</div>
                </div>
              </template>
            </a-upload>
          </a-form-item>
        </a-form>
      </a-modal>
    </div>
    <!-- 显示病例详情 -->
    <Caseimg v-if="dciomshow" :imgsrc="imgsrc" @goback="goback" />
  </div>
</template>

<script lang="ts" setup>
  import { computed, ref, reactive, watch, nextTick } from 'vue';
  import { useRouter } from 'vue-router';
  import useLoading from '@/hooks/loading';
  import {
    Message,
    Modal,
    TableColumnData,
    ValidatedError,
  } from '@arco-design/web-vue';
  import {
    typeList,
    databaseList,
    caseRemove,
    addDatabase,
    databaseUpdate,
    addimg,
    upload,
    imgList,
    addImglist,
  } from '@/api/caselist';
  import { Pagination } from '@/types/global';
  import Caseimg from './caseimg.vue';
  const { loading, setLoading } = useLoading(true);
  // 定义查看 是否 图片
  const dciomshow = ref(false);
  // 钩子
  const generateFormModel = () => {
    return {
      caseName: '',
      caseTypeId: '',
    };
  };

  const base = ref((window as any).config.VUE_APP_IMG_API);
  const formModel = ref(generateFormModel());

  //   添加
  const renderData = ref([]);
  //   定义查询接口
  const fetchData = async () => {
    setLoading(true);
    try {
      const data = {
        pageNum: pagination.current,
        ...pagination,
        ...formModel.value,
      };
      databaseList(data).then((res) => {
        renderData.value = res.data.list;
        pagination.total = res.data.total;
        pagination.current = res.data.pageNum;
      });
    } catch (err) {
      console.log(err);
    } finally {
      setLoading(false);
    }
  };

  //   定义相关参数
  const basePagination: Pagination = {
    current: 1,
    pageSize: 10,
    total: 0,
  };
  const pagination = reactive({
    ...basePagination,
    'hide-on-single-page': true,
    'show-total': true,
    'show-jumper': true,
    'show-page-size': true,
  });
  //   查找 充实

  const onPageChange = (current: number) => {
    pagination.current = current;
    fetchData();
  };
  const onPageSizeChange = (pageSize: number) => {
    pagination.pageSize = pageSize;
    fetchData();
  };
  const caseIds = ref([]);
  //   重置
  const reset = () => {
    formModel.value = generateFormModel();
    fetchData();
  };

  fetchData();

  const columns = computed<TableColumnData[]>(() => [
    {
      title: 'ID',
      dataIndex: 'caseId',
    },
    {
      title: '封面',
      dataIndex: 'url',
      slotName: 'url',
    },
    {
      title: '病例名称',
      dataIndex: 'caseName',
    },
    {
      title: '分类名称',
      dataIndex: 'caseTypeName',
    },

    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
    {
      title: '创建人',
      dataIndex: 'createUserName',
    },

    {
      title: '功能',
      slotName: 'option',
    },
  ]);
  const openDelete = (item: any) => {
    Modal.confirm({
      title: '提示',
      content: '确认删除吗？',
      onOk() {
        caseRemove({
          caseId: item.caseId,
        }).then((res: any) => {
          if (res.code == '200') {
            Message.success({
              //   content: res.message,
              content: '删除成功',
            });
            fetchData();
          }
        });
      },
    });
  };
  const addShow = ref(false);
  //   新增
  const openAdd = () => {
    addShow.value = true;
  };

  const rules = {
    caseName: [
      {
        required: true,
        message: '请输入病例名称',
      },
      {
        maxLength: 20,
        message: '最长20位',
      },
    ],
    url: [
      {
        required: true,
        message: '请上传病例封面',
      },
    ],
    caseTypeId: [
      {
        required: true,
        message: '请选择分类',
      },
    ],
    situation: [
      {
        required: true,
        message: '请输入患者情况',
      },
    ],
    imgFeatures: [
      {
        required: true,
        message: '请输入影像表现',
      },
    ],
    diagnosticConclusion: [
      {
        required: true,
        message: '请输入诊断结论',
      },
    ],
    status: [
      {
        required: true,
        message: '请选择是否开启',
      },
    ],
  };
  const generateDataModel = () => {
    return {
      caseName: '',
      url: '',
      caseId: 0,
      caseTypeId: '',
      situation: '',
      imgFeatures: '',
      diagnosticConclusion: '',
      status: 0,
    };
  };
  const addForm = ref(generateDataModel());

  const handleCancel = () => {
    addForm.value = generateDataModel();
  };
  const addModel = ref();
  const handleCheck = (done: (arg0: boolean) => void) => {
    if (loading.value) {
      done(false);
      return;
    }
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
    }, 1500);
    addModel.value.validate(
      async (errors: undefined | Record<string, ValidatedError>) => {
        if (!errors) {
          if (addForm.value.caseId != 0) {
            console.log('走的编辑', addForm.value.caseTypeId);

            databaseUpdate(addForm.value).then((res: any) => {
              if (res.code == '200') {
                Message.success({
                  //   content: res.message,
                  content: '编辑成功',
                });
                addForm.value = generateDataModel();
                done(true);
                fetchData();
              } else {
                done(false);
              }
            });
          } else {
            addDatabase(addForm.value).then((res: any) => {
              if (res.code == '200') {
                Message.success({
                  //   content: res.message,
                  content: '新增成功',
                });
                addForm.value = generateDataModel();
                done(true);
                fetchData();
              } else {
                done(false);
              }
            });
          }
        } else {
          done(false);
        }
      }
    );
  };

  //   处理图片进度
  const tponProgress = (currentFile: any) => {
    let formData = new FormData();
    formData.append('file', currentFile.file);
    addimg(formData).then((res: any) => {
      if (res.code == 200) {
        addForm.value.url = res.data;
        addModel.value.validateField('url');
        console.log('上传成功', res.data);
      }
    });
  };
  //   图片加载失败
  const handleImgError = (event: any) => {
    console.log(event, '出发');

    event.target.src = '/public/error.png'; // 设置占位图片
  };

  const openEdit = (item: any) => {
    addForm.value = Object.assign({}, item);
    addShow.value = true;
    console.log('重置后的数据', addForm.value);
  };

  //   查询分类名称
  const typedata = ref([]);
  const typeListfn = () => {
    typeList({ pageSize: 999, pageNum: 1 }).then((res) => {
      typedata.value = res.data.list;
    });
  };
  typeListfn();
  const uploadRef = ref(null);

  const fileList = ref();

  const customRequest = (option: any, caseId: any) => {
    const { onProgress, onError, onSuccess, fileItem, name, handleRemove } =
      option;
    console.log('上传图像', fileItem.file);
    let formData = new FormData();
    formData.append('caseId', caseId);
    formData.append('file', fileItem.file);
    upload(formData)
      .then((res: any) => {
        if (res.code == 200) {
          onSuccess();
          console.log('图像上传成功', option);

          // 再次调用存进去
          addImglist({ caseId: caseId, urlList: res.data }).then(
            (ress: any) => {
              if (ress.code == 200) {
                console.log('存储成功');

                fetchData();
              }
            }
          );
        }
      })
      .catch((err: any) => {
        onError(err);
      });
    return {
      abort: () => {
        console.log('上传已取消');
      },
    };
  };
  const imgsrc = ref([]);
  const checksee = (caseId: any) => {
    imgList({ caseId: caseId }).then((res: any) => {
      if (res.code == 200) {
        imgsrc.value = res.data;
        if (res.data.length > 0) {
          dciomshow.value = true;
        } else {
          Message.error('当前病例暂未上传病例详情图');
        }
      }
    });
  };
  const goback = () => {
    dciomshow.value = false;
  };
</script>

<style scoped>
  .imgbox {
    width: 50px;
    height: 50px;
    overflow: hidden;
  }
  .imgbox img {
    width: 50px;
    height: 50px;
  }
</style>
